package com.eascs.web.o2o.web.filter;


import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.SqlFilter;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.sys.SysOrgService;

/**
 * 数据权限过滤器 如果是信贷经理看自己, 区域经理看自己管理的信贷经理, 信贷专员看自己管理的信贷经理 ,如果有省区角色，走原来平台权限
 * 
 * @author user
 *
 */
@Component
public class DataPermissionUseCMFilter implements SqlFilter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	/** 权限关键字 */
	/// **DATA_PERMISSION(OL.LTD)**/
	private static final String DATA_PERMISSION_KEY = "DATA_CE_PERMISSION";
	private static final String SQL_PATTERN_STR = "^.*(\\/\\*\\*DATA_CE_PERMISSION\\((.+),(.+),(.+)\\)\\*\\*\\/).*$";
	public static final Pattern SQL_PATTERN = Pattern.compile(SQL_PATTERN_STR);
	@Reference
	SysOrgService sysOrgService;

	@Override
	public String filterSql(String sql) {
		User user = UserHolder.getUser();
		if (StringUtils.contains(sql, DATA_PERMISSION_KEY) && user != null) {
			Matcher mather = SQL_PATTERN.matcher(sql);
			if (mather.matches()) {
				String block = mather.group(1);
				String unitNoColum = mather.group(2);
				String creatorColum = mather.group(3);
				String operatorColum = mather.group(4);
				// 获取可以查看的人
				List<User> userList = sysOrgService.checkDataPermission(user.getNo());
				// 为空，走原来平台权限
				if (CollectionUtils.isEmpty(userList)) {
					String permissionStr = StringUtils.replace(user.getDataPermissionStr(), "/**PERMISSION_COLUM**/",
							unitNoColum);
					String sqlStr = StringUtils.replace(sql, block, permissionStr);
					return sqlStr;
				} else {
					StringBuffer userNoBuf = new StringBuffer();
					for (User u : userList) {
						userNoBuf.append("'").append(u.getNo()).append("'").append(",");
					}
					String userNoParams = userNoBuf.substring(0, userNoBuf.length() - 1);
					String replaceBolock = " (" + creatorColum + " in (" + userNoParams + ") or " + operatorColum
							+ " in (" + userNoParams + ")) and ";
					String sqlStr = StringUtils.replace(sql, block, replaceBolock);
					return sqlStr;
				}
			}
		}
		return sql;
	}

	public static void main(String[] args) {
		String str = " SELECT DISTINCT * FROM (SELECT OL.BILLCODE,OL.CUSTOMERCODE||'-'||OL.CUSTOMERNAME, (SELECT HU.UNITCODE||'-'||HU.NAMECN AS NAMECN FROM EADB.HR_UNITS HU WHERE /**DATA_CE_PERMISSION(HU.UNITNO,HU.CREATOR,HU.OPERATOR)**/ HU.UNITNO = OL.LTD) NAMECN,ORF.LOANERNAME,(SELECT PDD.ITEMNAME FROM EADB.PUB_DDITEM PDD JOIN EADB.PUB_DATADICTIONARY PD ON PDD.DDNO=PD.DDNO  WHERE PD.DDCODE='OTOREPAYMENTWAY' AND OL.REPAYMENTWAY = PDD.ITEMCODE) ITEMNAME,  OL.LOANRATE*100,OL.LOANTERM,OL.LOANAMOUNT,ORFU.BANKLOANAMOUNT,OL.OPERATORNAME  FROM EADB.O2O_LOANAPPLY OL JOIN EADB.O2O_REFUND ORF ON OL.BILLCODE=ORF.LOADAPPLYCODE JOIN EADB.O2O_REFUNDLINE ORFL ON ORFL.REFUNDNO = ORF.REFUNDNO  LEFT JOIN EADB.O2O_REFUND ORFU ON ORFU.LOADAPPLYCODE = OL.BILLCODE WHERE ORFU.ISLOCK='N' AND ORFU.BANKREFUNDCODE <> 'GACZ') T WHERE 1=1  ORDER BY T.BILLCODE DESC ";
		Matcher mather = SQL_PATTERN.matcher(str);
		if (mather.matches()) {
			String block = mather.group(1);
			String unitNoColum = mather.group(2);
			String creatorColum = mather.group(3);
			String operatorColum = mather.group(4);
			String sqlStr = StringUtils.replace(str, "/**DATA_PERMISSION" + mather.group(1) + "**/", "xxxxx");
			System.out.println(sqlStr);
		}
	}
}
